package com.xmjs.baselibrary.network.retrofit;

import com.xmjs.baselibrary.BuildConfig;
import com.xmjs.baselibrary.base.application.LibBaseApplication;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

/**
 * https证书认证工具类
 */
public class HttpsUtil {

    static HttpsUtil mHttpsUtil;

    private HttpsUtil() {

    }

    public static HttpsUtil getIntance() {
        if (mHttpsUtil == null)
            mHttpsUtil = new HttpsUtil();
        return mHttpsUtil;
    }

    // 设置证书
    public SSLSocketFactory setCertificates() {
        try {
            // 读取证书
            InputStream inputStream = LibBaseApplication.getContext().getAssets().open("ssl_certificate.pem");
            //根据公钥证书生产Certificate对象
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            Certificate certificate = certificateFactory.generateCertificate(inputStream);
            //创建一个证书库，并将证书导入证书库
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            keyStore.setCertificateEntry(BuildConfig.APPLICATION_ID, certificate);
            //及时关闭输入流
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 创建一个证书管理器，并将证书库导入
            TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            // 创建一个使用我们证书管理器的SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());

            return sslContext.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
